package com.csxy.mx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.mx.entity.EduCourse;
import com.csxy.mx.entity.EduCourseDescription;
import com.csxy.mx.entity.vo.*;
import com.csxy.mx.exception.MyException;
import com.csxy.mx.mapper.EduCourseMapper;
import com.csxy.mx.service.EduChapterService;
import com.csxy.mx.service.EduCourseService;
import com.csxy.mx.service.EduVideoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService { // 添加接口实现
    
    @Autowired
    private EduCourseDescriptionServiceImpl eduCourseDescriptionService;
    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private EduChapterService eduChapterService;

    @Override
    // 添加课程信息
    public String addCourseInfo(CourseInfoForm courseInfoForm) {
//    向课程表里添加课程基本信息
//    把courseInfoForm对象转换成EduCourse对象
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoForm, eduCourse);
        int result = baseMapper.insert(eduCourse);

//        if (result == 0) {
//            // 插入失败处理（可抛出自定义异常）
//            // throw new GuliException(20001, "添加课程信息失败");
//            return null;
//        }
//

//    获取添加之后课程信息的ID
        String cid = eduCourse.getId();
//        向课程简介表里面添加课程简介

        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoForm.getDescription());
//        手动设置描述课程表的ID，与上面的课程信息表ID关联
        eduCourseDescription.setId(cid);
        // 保存课程描述信息到数据库
        eduCourseDescriptionService.save(eduCourseDescription);

        return cid;
    }

    @Override
    public CourseInfoForm getCourseInfoById(String courseId) {
        CourseInfoForm courseInfoForm = new CourseInfoForm();
        EduCourse eduCourse = baseMapper.selectById(courseId);
        if (eduCourse == null) {
            throw new MyException(20001, "课程不存在");
        }
        BeanUtils.copyProperties(eduCourse, courseInfoForm);
        
        // 安全地获取课程描述，避免空指针异常
        EduCourseDescription courseDescription = eduCourseDescriptionService.getById(courseId);
        if (courseDescription != null) {
            courseInfoForm.setDescription(courseDescription.getDescription());
        } else {
            courseInfoForm.setDescription(""); // 如果没有描述，设置为空字符串
        }
        return courseInfoForm;
    }

    @Override
    public void updateCourseInfo(CourseInfoForm courseInfoForm) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoForm, eduCourse);
        baseMapper.updateById(eduCourse);

        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoForm.getDescription());
        eduCourseDescription.setId(courseInfoForm.getId());
        eduCourseDescriptionService.updateById(eduCourseDescription);
    }


    @Override
    public boolean removeCourseById(String id) {
        eduVideoService.removeVideoByCourseId(id);
        eduChapterService.removeChapterByCourseId(id);
        eduCourseDescriptionService.removeById(id);
        int result = baseMapper.deleteById(id);
        if (result>=1) {
            return true;
        }else {
            throw new MyException(20001, "删除失败");
        }
    }

    @Override
    public void pageQuery(Page<EduCourse> pageParam, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        String title = courseQuery.getTitle();
        String status = courseQuery.getStatus();
        if (!title.isEmpty() ){
            queryWrapper.like("title",title);
        }
        if (!title.isEmpty()){
            queryWrapper.eq("status",status);
        }
        queryWrapper.orderByDesc("get_modified");
        baseMapper.selectPage(pageParam,queryWrapper);
    }
    @Autowired
    private EduCourseMapper eduCourseMapper;
    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        return eduCourseMapper.getPublishCourseInfo(id);
    }

    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }

    @Override
    public List<EduCourse> selectHotCourse() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "Normal"); // 只查询已发布的课程
        wrapper.orderByDesc("view_count");
        wrapper.last("limit 8");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> getCourseFrontInfo(Page<EduCourse> pageCourse, CourseFrontVo courseFrontVo) {
        // 构建条件查询
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(courseFrontVo.getSubjectParentId())){
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if(StringUtils.isNotEmpty(courseFrontVo.getSubjectId())){
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(StringUtils.isNotEmpty(courseFrontVo.getBuyCountSort())){
            wrapper.orderByDesc("buy_count");
        }
        if(StringUtils.isNotEmpty(courseFrontVo.getPriceSort())){
            wrapper.orderByDesc("price");
        }
        if(StringUtils.isNotEmpty(courseFrontVo.getGmtCreateSort())){
            wrapper.orderByDesc("gmt_create");
        }
        eduCourseMapper.selectPage(pageCourse, wrapper);
        Map<String, Object> map = new HashMap<>();
        long total = pageCourse.getTotal(); // 总记录数
        List<EduCourse> courseList = pageCourse.getRecords(); // 数据集合
        long size = pageCourse.getSize(); // 每页记录数
        long current = pageCourse.getCurrent(); // 当前页
        long pages = pageCourse.getPages(); // 总页数
        boolean hasPrevious = pageCourse.hasPrevious(); // 是否有上一页
        boolean hasNext = pageCourse.hasNext(); // 是否有下一页
        map.put("total", total);
        map.put("list", courseList);
        map.put("size", size);
        map.put("current", current);
        map.put("pages", pages);
        map.put("hasPrevious", hasPrevious);
        map.put("hasNext", hasNext);
        return map;
    }
}
